package com.tc.nio;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import static com.tc.util.ByteBufferUtil.debugAll;

/**
 * @Auther: tianchao
 * @Date: 2022/1/29 16:51
 * @Description:
 */
public class TestByteBufferString {
    public static void main(String[] args) {
        //1 字符串转为byteBuffer
        String str = "hello world";
        ByteBuffer byteBuffer = ByteBuffer.allocate(20);
        byteBuffer.put(str.getBytes());
        debugAll(byteBuffer);
        //2 Charset
        Charset charset = StandardCharsets.UTF_8;
        //自动变为读模式
        byteBuffer = charset.encode(str);
        debugAll(byteBuffer);
        debugAll(byteBuffer);
        //3 wrap
        byteBuffer = ByteBuffer.wrap(str.getBytes());
        debugAll(byteBuffer);

        // 解密的方法参数必须是读模式的状态下才能有效
        CharBuffer decode = StandardCharsets.UTF_8.decode(byteBuffer);
        System.out.println(decode.toString());
    }


}

